package com.pervasa.demo.kitsample.impl;

import java.util.Vector;

public class CompositeEvent extends EventTree {
	public CompositeEvent(Operator op)
	{
		this.op = op;
	}
	public Vector<EventTree> getChildren()
	{
		return children;
	}
	
	private Vector<EventTree> children = new Vector<EventTree>();
	private Operator op = null;
	public static Operator orOp = new CompositeEvent.OrOperator();
	public static Operator andOp = new AndOperator();
	
	
	public static abstract class Operator
	{
		public abstract TRUTH evaluate(Vector<TRUTH> results) throws NoChildrenException;
	}
	
	public static class AndOperator extends Operator
	{
		public AndOperator()
		{
			
		}
		public TRUTH evaluate(Vector<TRUTH> results) throws NoChildrenException
		{
			if (results.size() == 0)
				throw new NoChildrenException();
			
			if (results.contains(TRUTH.FALSE))
				return TRUTH.FALSE;
			else if (results.contains(TRUTH.UNKNOWN))
				return TRUTH.UNKNOWN;
			else
				return TRUTH.TRUE;
		}
	}
	
	public static class OrOperator  extends Operator
	{
		public OrOperator()
		{
			
		}
		public TRUTH evaluate(Vector<TRUTH> results) throws NoChildrenException
		{
			if (results.size() == 0)
				throw new NoChildrenException();
			
			if (results.contains(TRUTH.TRUE))
				return TRUTH.TRUE;
			else if (results.contains(TRUTH.UNKNOWN))
				return TRUTH.UNKNOWN;
			else
				return TRUTH.FALSE;
		}
	}

	@Override
	public TRUTH evaluate() throws NoChildrenException {
		Vector<TRUTH> results = new Vector<TRUTH>();
		for (int i = 0; i < getChildren().size(); i++)
		{
			results.add(getChildren().get(i).evaluate());
		}
		
		return op.evaluate(results);
	}
}
